#include "pub_sqthread.h"
#include "pub_var.h"
#include <QSqlQuery>
#include <QSqlError>
//#include <QDebug>
void sqThread::run()
{

    QString retStr = "finish";
    int count = 0;
    error_state = false;

    pub::db_o.transaction();
    pub::db_m.transaction();

    foreach(QString sq, sqls)
    {
        QString flag = sq.left(1);
        QString rsq = sq.right(sq.length()-1);

        emit message( "msg^" +  QString::number(count));
        if( flag == "o")
        {
           pub::db_o.exec(rsq);
           if(pub::db_o.lastError().isValid())
           {
               retStr = "error : " + pub::db_o.lastError().text();
               error_state = true;
               qDebug()<<"sql error in thread : "<<rsq;
               break;
           }
        }
        else if(flag == "m")
        {
            pub::db_m.exec(rsq);
            if(pub::db_m.lastError().isValid())
            {
                retStr = "error : " + pub::db_m.lastError().text() ;
                error_state = true;
                qDebug()<<"sql error in thread : "<<rsq;
                break;
            }
        }
        else
        {
            retStr = "error : 数据库标志错误 ！" ;
            error_state = true;
            break;
        }
        count ++;
    }

    if(error_state)
    {
        emit message( "rollback" );
        pub::db_o.rollback();
        pub::db_m.rollback();
    }
    else
    {
        pub::db_o.commit();
        pub::db_m.commit();
    }
    emit message( retStr );

    currentThread()->exit(0);

}

sqThread::sqThread()
{
    //qrM = new QSqlQuery(pub::db_m);
    //qrO = new QSqlQuery(pub::db_o);
}

void sqThread::setSqls(QStringList s)
{
    sqls = s;
}

sqThread::~sqThread()
{
    //delete qrM;
    //delete qrO;
}

bool sqThread::getLastError()
{
    return error_state;
}
